import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';

class ImageExtens {
  static Widget assetSvg(String name) {
    return name.endsWith("svg") ? SvgPicture.asset(name) : Image.asset(name);
  }
}

//封装图片加载控件，增加图片加载失败时加载默认图片
class ImageX extends StatefulWidget {
  ImageX(
      {this.url = '',
      this.image,
      this.w,
      this.h,
      this.fit = BoxFit.cover,
      this.defImagePath = "assets/images/ic_launcher.png"});

  Image? image;
  final String url;
  final double? w;
  final double? h;
  final BoxFit fit;

  final String defImagePath;

  @override
  State<StatefulWidget> createState() {
    return _StateImageWidget(image);
  }
}

class _StateImageWidget extends State<ImageX> {
  late Image _image;

  _StateImageWidget(Image? image) {
    _image = image ??
        Image.network(
          widget.url,
          fit: widget.fit,
          width: widget.w,
          height: widget.h,
        );
  }

  @override
  void initState() {
    super.initState();
    var resolve = _image.image.resolve(ImageConfiguration.empty);
    resolve.addListener(ImageStreamListener((_, __) {
      //加载成功
    }, onError: (exception, stackTrace) {
      //加载失败
      setState(() {
        _image = Image.asset(
          widget.defImagePath,
          width: widget.w,
          height: widget.h,
        );
      });
    }));
  }

  @override
  Widget build(BuildContext context) {
    return _image;
  }
}
